package com.qj.daibei.controller;

import com.github.pagehelper.PageInfo;
import com.qj.daibei.pojo.*;
import com.qj.daibei.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * author wml
 * Created on 2021/10/26 22:30
 */
@Controller
public class RepaymentController {

    @Autowired
    private RepaymentService repaymentService;

    private ShouldPayBackService shouldPayBackService;

    @Autowired
    public void setShouldPayBackService(ShouldPayBackService shouldPayBackService) {
        this.shouldPayBackService = shouldPayBackService;
    }

    @Autowired
    private RepaymentCustomTestService repaymentCustomTestService;

    @Autowired
    private OverdueService overdueService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/insertRepayment", method = RequestMethod.POST)
    @ResponseBody
    public boolean insertRepayment(Repayment repayment, ShouldPayBack shouldPayBack, HttpSession session) {
        // 获取session里的User
        User user = (User) session.getAttribute("loginUser");
        // 设置还款表的还款时间为现在
        repayment.setRepaymentTime(new Date());
        // 设置还款表的还款用户
        repayment.setUserId(user.getUserId());
        // 设置待还款表的状态
        shouldPayBack.setSpbStatus("已还款");
        // 如果oid != null 则为逾期还款
        if (repayment.getOId() != null) {
            Overdue overdue = new Overdue();
            // 获取逾期表的oid
            overdue.setOId(repayment.getOId());
            // 设置逾期表的还款状态
            overdue.setOStatus("已还款");
            // 修改逾期表的还款状态
            this.overdueService.updateOverdueById(overdue);
            user.setPinMoney(user.getPinMoney() - shouldPayBack.getSpbMoney() - 100);
        } else {
            user.setPinMoney(user.getPinMoney() - shouldPayBack.getSpbMoney());
        }
        // 修改待还款表的还款状态
        int result = this.shouldPayBackService.updateShouldPayBackById(shouldPayBack);
        // 插入已还款记录
        boolean flag = this.repaymentService.insertRepayment(repayment);
        // 修改用户表的零钱
        this.userService.updatePinMoneyByUserId(user);
        System.out.println("Repayment repayment:" + repayment);
        System.out.println("ShouldPayBack shouldPayBack:" + shouldPayBack);
        if (result == 1 && flag == true) return true;
        else return false;
    }

    @RequestMapping(value = "/getRepaymentCustom", method = RequestMethod.GET)
    @ResponseBody
    public PageInfo<RepaymentCustomTest> getRepaymentCustom(int pageNum, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        return this.repaymentCustomTestService.findRepaymentAndShouldPayBackAndLoanByPage(pageNum, user.getUserId());
    }
}
